package cn.hd01.web.config;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthDelegate;
import cn.hd01.web.auth.AuthType;

public class AuthInterceptor extends HandlerInterceptorAdapter {
	private AuthDelegate delegate;

	public AuthInterceptor(AuthDelegate delegate) {
		this.delegate = delegate;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Auth auth = getAuthType(((HandlerMethod) handler).getMethod());

		if (auth == null) {
			response.sendError(HttpStatus.NOT_FOUND.value());
			return false;
		}

		if (auth.value() == AuthType.OFF) {
			return true;
		}

		return delegate.authenticate(request, response, auth.value());
	}

	private Auth getAuthType(Method method) {
		if (method.isAnnotationPresent(Auth.class)) {
			return method.getAnnotation(Auth.class);
		}

		Class<?> clazz = method.getDeclaringClass();
		if (clazz.isAnnotationPresent(Auth.class)) {
			return clazz.getAnnotation(Auth.class);
		}

		return null;
	}
}
